<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :permission="permissionList"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 @on-load="getList"
                 @search-change="searchChange"
                 @refresh-change="refreshChange"
                 @size-change="sizeChange"
                 @current-change="currentChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @search-reset="searchReset"
                 @row-del="rowDel">
        <template slot="menuLeft">
          <el-button
            v-if="permissions.admin_sysgrayitem_add"
            class="filter-item"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleCreate">新增节点
          </el-button>
        </template>
        <template
          slot-scope="scope"
          slot="menu">
          <el-button
            v-if="permissions.admin_sysfrontgray_add_edit"
            type="text"
            size="small"
            icon="el-icon-menu"
            @click="setItem(scope.row)">设置
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-menu"
            @click="handleItem(scope.row,scope.index)">关系
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      :visible.sync="dialogFormVisible"
      title="灰度规则"
      width="90%"
      @close="FrontItemVisible">
      <avue-crud ref="crudItem"
                 :page="itemPage"
                 :data="tableFrontGrayData"
                 :permission="permissionList"
                 :option="tableFrontGrayOption"
                 @refresh-change="refreshChangeFront"
      >
        <template
          slot="deptId"
          slot-scope="scope">
              <span
                v-for="(dept,index) in scope.row.sysDepts"
                :key="index">
                <el-tag>{{ dept.name }} </el-tag>&nbsp;&nbsp;
              </span>
        </template>
        <template
          slot="role"
          slot-scope="scope">
              <span
                v-for="(role,index) in scope.row.sysRoles"
                :key="index">
                <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
              </span>
        </template>
        <template
          slot-scope="scope"
          slot="menu">
          <el-button
            v-if="permissions.admin_sysfrontgray_add_edit"
            type="text"
            size="small"
            icon="el-icon-menu"
            @click="editFrontGray(scope.row)">编辑
          </el-button>
          <el-button
            v-if="permissions.admin_sysfrontgray_del"
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="deleteFrontGray(scope.row)">删除
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog :visible.sync="dialogFrontGrayVisible" @closed="dialogClosed" :close-on-click-modal="false"
               title="灰度规则">
      <el-form ref="itemForm" :model="form" label-width="80px">
        <el-form-item
          prop="frontSign"
          label="前端标识"
          :rules="[
              { required: true, message: '请输入前端标识', trigger: 'blur' }
               ]"
        >
          <el-input v-model="form.frontSign" maxlength="20" required="true" placeholder="请输入前端标识"   show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="服务名称">
          <el-input v-model="form.springApplicationName" disabled="disabled" required="true"></el-input>
        </el-form-item>

        <el-form-item label="所属角色">
          <avue-select
            filterable
            v-model="form.roleIds"
            :dic="treeRoleData"
            :props="roleProps"
            multiple
            placeholder="请选择所属角色"/>
        </el-form-item>
        <!--<el-form-item label="所属部门">-->
        <!--<avue-input-->
        <!--filterable-->
        <!--multiple-->
        <!--v-model="form.deptIds"-->
        <!--:dic="treeDeptData"-->
        <!--:props="defaultProps"-->
        <!--type="tree"-->
        <!--placeholder="请选择所属部门"/>-->
        <!--</el-form-item>-->
        <el-form-item label="所属部门">
          <el-tree
            v-model="form.deptIds"
            ref="scopeTree" :data="treeDeptData" :check-strictly="true" :props="defaultProps"
            class="filter-tree" node-key="id" highlight-current  @check-change="checkNode"
            show-checkbox/>
        </el-form-item>

        <!--<el-form-item-->
        <!--prop="outTime"-->
        <!--label="有效时间"-->
        <!--type="number"-->
        <!--:rules="[-->
        <!--{ required: true, message: '请输入有效时间(天)', trigger: 'blur' },-->
        <!--{ min: 1, max: 10, message: '长度在 1 到 10 个数字', trigger: 'blur' }-->
        <!--]"-->
        <!--&gt;-->
        <!--<el-input v-model="form.outTime" type="number" min="1" onkeyup="this.value=this.value.replace(/\D|^0/g,'')"-->
        <!--placeholder="请输入有效时间(天)" maxlength="10" show-word-limit></el-input>-->
        <!--</el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="submitForm('itemForm')">提交</el-button>
          <el-button @click="dialogClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchList, getObj, addObj, putObj, delObj, fetchItemList, bindFrontGray, delFrontGray} from '@/api/admin/gray'
  import {tableOption, tableFrontGrayOption} from '@/const/crud/admin/gray'
  import {mapGetters} from 'vuex'
  import config from "@/config/app"
  import {fetchTree} from '@/api/admin/dept'
  import {deptRoleList} from '@/api/admin/role'

  export default {
    name: 'sysgrayitem',
    data() {
      return {
        form: {
          id:'',
          frontSign: '',
          springApplicationName: '',
          deptIds: '',
          roleIds: '',
          sysGrayItemId: '',
          outTime: ''
        },
        checkedDeptScope: [],
        itemData: {},
        searchForm: {},
        tableData: [],
        tableFrontGrayData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        itemPage: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        tableFrontGrayOption: tableFrontGrayOption,
        dialogFormVisible: false,
        dialogFrontGrayVisible: false,
        springApplicationName:'',
        treeDeptData: [], //部门
        defaultProps: {
          label: 'name',
          value: 'deptId'
        },
        treeRoleData: [],//角色
        roleProps: {
          label: 'roleName',
          value: 'roleId'
        },
        sysGrayItemId: ''
      }
    },
    computed: {
      ...mapGetters(['permissions']),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.admin_sysgrayitem_add, false),
          delBtn: this.vaildData(this.permissions.admin_sysgrayitem_del, false),
          editBtn: this.vaildData(this.permissions.admin_sysgrayitem_edit, false)
        };
      }
    },
    methods: {
      getList(page, params) {
        this.tableLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      rowDel: function (row, index) {
        this.$confirm('是否确认删除该数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          this.$message.success('删除成功')
          this.getList(this.page)
        })
      },
      handleUpdate: function (row, index, done, loading) {
        putObj(row).then(data => {
          this.$message.success('修改成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading();
        });
      },
      handleSave: function (row, done, loading) {
        addObj(row).then(data => {
          this.$message.success('添加成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading();
        });
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      refreshChange() {
        this.getList(this.page)
      },
      searchReset() {
        this.searchForm = {}
        this.page.currentPage = 1
        this.getList(this.page)
      },
      handleCreate() {
        this.$refs.crud.rowAdd()
      },

      //------------关系-----------
      refreshChangeFront() {
        this.getDictItemList(this.form.sysGrayItemId)
      },
      FrontItemVisible: function () {
        this.dialogFormVisible = false
        this.itemPage.currentPage = 1
      },
      handleItem: function (row) {
        this.form.sysGrayItemId = row.id;
        this.springApplicationName=row.springApplicationName;
        this.getDictItemList(row.id)
      },
      getDictItemList(sysGrayItemId) {
        this.dialogFormVisible = true
        fetchItemList(Object.assign({
          current: this.itemPage.currentPage,
          size: this.itemPage.pageSize
        }, {sysGrayItemId: sysGrayItemId})).then(response => {
          this.tableFrontGrayData = response.data.data.records
          this.itemPage.total = response.data.data.total
        })
      },
      setItem: function (row) {
        this.form.id='';
        this.form.sysGrayItemId = row.id;
        this.form.springApplicationName = row.springApplicationName;
        this.handleDept();
        this.getNodeData();
        this.$nextTick(() => {
          this.$refs.scopeTree.setCheckedKeys([]);
        });
        this.dialogFrontGrayVisible = true;
      },
      //部门
      handleDept() {
        fetchTree().then(response => {
          this.treeDeptData = response.data.data
        })
      },
      //xiaobei added
      checkNode(node, checked, c) {
        if (node.children && node.children.length) {
          this.$refs.scopeTree.setChecked(node.id, checked,)
          node.children.forEach(item => {
            this.$refs.scopeTree.setChecked(item.id, checked,)
          })
        }
      },
      //角色
      getNodeData() {
        deptRoleList().then(response => {
          this.treeRoleData = response.data.data
        })
      },
      //重置
      dialogClosed() {
          this.form.deptIds = '',
          this.form.roleIds = '',
          this.form.outTime = '',
          this.form.frontSign = ''
          this.dialogFrontGrayVisible = false;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.itemData.id=  this.form.id,
            this.itemData.frontSign = this.form.frontSign,
            this.itemData.sysGrayItemId = this.form.sysGrayItemId,
            this.itemData.deptIds = this.$refs.scopeTree.getCheckedKeys().join(',')
            this.itemData.roleIds = this.form.roleIds.toString(), this.itemData.outTime = this.form.outTime
            console.log(this.itemData);
            bindFrontGray(this.itemData).then(() => {
              this.$message.success('操作成功')
              this.dialogFrontGrayVisible = false;
              this.dialogClosed();
              if(!this.form.id==''){
                this.getDictItemList( this.itemData.sysGrayItemId)
              }

            }).catch(() => {

            })
          } else {
            return false;
          }
        });
      },
      editFrontGray(row) {
        this.form.id=row.id;
        this.form.sysGrayItemId=row.sysGrayItemId;
        this.form.frontSign=row.frontSign;
        this.form.springApplicationName = this.springApplicationName;
        var roleIdArr=[];
        row.sysRoles.filter(function(item){
          roleIdArr.push(item.roleId)
        })
        var deptIdArr=[];
        row.sysDepts.filter(function(item){
          deptIdArr.push(item.deptId)
        })
        this.handleDept();
        this.getNodeData();
        this.form.roleIds =roleIdArr;
        this.$nextTick(() => {
          this.$refs.scopeTree.setCheckedKeys(deptIdArr);
        });
        this.dialogFrontGrayVisible = true;
      },

      deleteFrontGray(row) {
        this.$confirm('是否确认删除该数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delFrontGray(row.id)
        }).then(data => {
          this.$message.success('删除成功')
          this.getDictItemList(row.sysGrayItemId)
        })
      },
    }
  }
</script>
